package ynu.edu.controller;

import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import ynu.edu.dto.OrderDTO;
import ynu.edu.dto.OrderRequestDTO;
import ynu.edu.entities.BaseResponse;
import ynu.edu.service.OrderService;

import java.util.List;

/**
 * 订单控制器
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    /**
     * 创建订单
     */
    @PostMapping
    @CircuitBreaker(name = "orderServiceBreaker", fallbackMethod = "createOrderFallback")
    public ResponseEntity<BaseResponse<OrderDTO>> createOrder(@RequestBody OrderRequestDTO orderRequest) {
        OrderDTO result = orderService.createOrder(orderRequest);
        return ResponseEntity.status(HttpStatus.CREATED)
                .body(BaseResponse.success(result));
    }
    
    /**
     * 创建订单 - 兼容前端API路径
     */
    @PostMapping("/create")
    @CircuitBreaker(name = "orderServiceBreaker", fallbackMethod = "createOrderFallback")
    public ResponseEntity<BaseResponse<OrderDTO>> createOrderWithPath(@RequestBody OrderRequestDTO orderRequest) {
        try {
            System.out.println("接收到订单创建请求: " + orderRequest);
            
            // 验证请求参数
            if (orderRequest.getUserId() == null || orderRequest.getUserId().isEmpty()) {
                System.out.println("订单创建失败: 用户ID为空");
                return ResponseEntity.badRequest()
                        .body(BaseResponse.error(400, "用户ID不能为空"));
            }
            
            if (orderRequest.getBusinessId() == null) {
                System.out.println("订单创建失败: 商家ID为空");
                return ResponseEntity.badRequest()
                        .body(BaseResponse.error(400, "商家ID不能为空"));
            }
            
            if (orderRequest.getDaId() == null) {
                System.out.println("订单创建失败: 地址ID为空");
                return ResponseEntity.badRequest()
                        .body(BaseResponse.error(400, "地址ID不能为空"));
            }
            
            // 检查订单明细
            if ((orderRequest.getOrderDetails() == null || orderRequest.getOrderDetails().isEmpty()) && 
                (orderRequest.getCartIds() == null || orderRequest.getCartIds().isEmpty())) {
                System.out.println("订单创建失败: 订单明细和购物车ID均为空");
                return ResponseEntity.badRequest()
                        .body(BaseResponse.error(400, "订单明细不能为空"));
            }
            
            // 创建订单
            System.out.println("开始创建订单...");
            OrderDTO result = orderService.createOrder(orderRequest);
            System.out.println("订单创建成功: " + result);
            
            return ResponseEntity.status(HttpStatus.CREATED)
                    .body(BaseResponse.success(result));
        } catch (Exception e) {
            System.out.println("订单创建异常: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(BaseResponse.error(500, "创建订单失败: " + e.getMessage()));
        }
    }

    /**
     * 获取订单详情
     */
    @GetMapping("/{orderId}")
    @CircuitBreaker(name = "orderServiceBreaker", fallbackMethod = "getOrderByIdFallback")
    public ResponseEntity<BaseResponse<OrderDTO>> getOrderById(@PathVariable("orderId") Integer orderId) {
        OrderDTO order = orderService.getOrderById(orderId);
        return ResponseEntity.ok(BaseResponse.success(order));
    }

    /**
     * 获取用户订单列表
     */
    @GetMapping("/user/{userId}")
    @CircuitBreaker(name = "orderServiceBreaker", fallbackMethod = "getOrdersByUserIdFallback")
    public ResponseEntity<BaseResponse<List<OrderDTO>>> getOrdersByUserId(@PathVariable("userId") String userId) {
        List<OrderDTO> orders = orderService.getOrdersByUserId(userId);
        return ResponseEntity.ok(BaseResponse.success(orders));
    }
    
    /**
     * 获取用户订单列表 - 兼容前端API路径
     */
    @GetMapping("/getByUserId/{userId}")
    @CircuitBreaker(name = "orderServiceBreaker", fallbackMethod = "getOrdersByUserIdFallback")
    public ResponseEntity<BaseResponse<List<OrderDTO>>> getOrdersByUserIdWithPath(@PathVariable("userId") String userId) {
        List<OrderDTO> orders = orderService.getOrdersByUserId(userId);
        return ResponseEntity.ok(BaseResponse.success(orders));
    }

    /**
     * 获取用户特定状态的订单列表
     */
    @GetMapping("/user/{userId}/status/{orderState}")
    @CircuitBreaker(name = "orderServiceBreaker", fallbackMethod = "getOrdersByUserIdAndStatusFallback")
    public ResponseEntity<BaseResponse<List<OrderDTO>>> getOrdersByUserIdAndStatus(
            @PathVariable("userId") String userId,
            @PathVariable("orderState") Integer orderState) {
        List<OrderDTO> orders = orderService.getOrdersByUserIdAndStatus(userId, orderState);
        return ResponseEntity.ok(BaseResponse.success(orders));
    }

    /**
     * 更新订单状态
     */
    @PutMapping("/{orderId}/status")
    @CircuitBreaker(name = "orderServiceBreaker", fallbackMethod = "updateOrderStatusFallback")
    public ResponseEntity<BaseResponse<OrderDTO>> updateOrderStatus(
            @PathVariable("orderId") Integer orderId,
            @RequestParam Integer orderState) {
        OrderDTO updatedOrder = orderService.updateOrderStatus(orderId, orderState);
        return ResponseEntity.ok(BaseResponse.success(updatedOrder));
    }
    
    /**
     * 更新订单状态 - 兼容前端API路径
     */
    @PutMapping("/status/{orderId}/{orderState}")
    @CircuitBreaker(name = "orderServiceBreaker", fallbackMethod = "updateOrderStatusFallback")
    public ResponseEntity<BaseResponse<OrderDTO>> updateOrderStatusWithPath(
            @PathVariable("orderId") Integer orderId,
            @PathVariable("orderState") Integer orderState) {
        OrderDTO updatedOrder = orderService.updateOrderStatus(orderId, orderState);
        return ResponseEntity.ok(BaseResponse.success(updatedOrder));
    }

    /**
     * 取消订单
     */
    @PutMapping("/{orderId}/cancel")
    @CircuitBreaker(name = "orderServiceBreaker", fallbackMethod = "cancelOrderFallback")
    public ResponseEntity<BaseResponse<OrderDTO>> cancelOrder(@PathVariable("orderId") Integer orderId) {
        OrderDTO cancelledOrder = orderService.cancelOrder(orderId);
        return ResponseEntity.ok(BaseResponse.success(cancelledOrder));
    }

    /**
     * 支付订单
     */
    @PutMapping("/{orderId}/pay")
    @CircuitBreaker(name = "orderServiceBreaker", fallbackMethod = "payOrderFallback")
    public ResponseEntity<BaseResponse<OrderDTO>> payOrder(@PathVariable("orderId") Integer orderId) {
        OrderDTO paidOrder = orderService.payOrder(orderId);
        return ResponseEntity.ok(BaseResponse.success(paidOrder));
    }

    /**
     * 完成订单
     */
    @PutMapping("/{orderId}/complete")
    @CircuitBreaker(name = "orderServiceBreaker", fallbackMethod = "completeOrderFallback")
    public ResponseEntity<BaseResponse<OrderDTO>> completeOrder(@PathVariable("orderId") Integer orderId) {
        OrderDTO completedOrder = orderService.completeOrder(orderId);
        return ResponseEntity.ok(BaseResponse.success(completedOrder));
    }
    
    /**
     * 获取订单详情及明细 - 兼容前端API路径
     */
    @GetMapping("/getWithDetail/{orderId}")
    @CircuitBreaker(name = "orderServiceBreaker", fallbackMethod = "getOrderByIdFallback")
    public ResponseEntity<BaseResponse<OrderDTO>> getOrderWithDetail(@PathVariable("orderId") Integer orderId) {
        OrderDTO order = orderService.getOrderById(orderId);
        return ResponseEntity.ok(BaseResponse.success(order));
    }
    
    /**
     * 获取完整订单信息 - 兼容前端API路径
     */
    @GetMapping("/getFullInfo/{orderId}")
    @CircuitBreaker(name = "orderServiceBreaker", fallbackMethod = "getOrderByIdFallback")
    public ResponseEntity<BaseResponse<OrderDTO>> getFullOrderInfo(@PathVariable("orderId") Integer orderId) {
        OrderDTO order = orderService.getOrderById(orderId);
        return ResponseEntity.ok(BaseResponse.success(order));
    }

    /**
     * 更新订单状态 - 兼容支付服务API调用
     */
    @PostMapping("/state")
    @CircuitBreaker(name = "orderServiceBreaker", fallbackMethod = "updateOrderStatusFallback")
    public ResponseEntity<BaseResponse<OrderDTO>> updateOrderStatePost(
            @RequestParam("orderId") Integer orderId,
            @RequestParam("orderState") Integer orderState) {
        System.out.println("收到POST请求更新订单状态，订单ID：" + orderId + "，状态：" + orderState);
        OrderDTO updatedOrder = orderService.updateOrderStatus(orderId, orderState);
        return ResponseEntity.ok(BaseResponse.success(updatedOrder));
    }

    // 降级方法

    public ResponseEntity<BaseResponse<OrderDTO>> createOrderFallback(OrderRequestDTO orderRequest, Exception e) {
        return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
                .body(BaseResponse.error(503, "创建订单失败，服务不可用: " + e.getMessage()));
    }

    public ResponseEntity<BaseResponse<OrderDTO>> getOrderByIdFallback(Integer orderId, Exception e) {
        return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
                .body(BaseResponse.error(503, "获取订单详情失败，服务不可用: " + e.getMessage()));
    }

    public ResponseEntity<BaseResponse<List<OrderDTO>>> getOrdersByUserIdFallback(String userId, Exception e) {
        return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
                .body(BaseResponse.error(503, "获取订单列表失败，服务不可用: " + e.getMessage()));
    }

    public ResponseEntity<BaseResponse<List<OrderDTO>>> getOrdersByUserIdAndStatusFallback(
            String userId, Integer orderState, Exception e) {
        return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
                .body(BaseResponse.error(503, "获取订单列表失败，服务不可用: " + e.getMessage()));
    }

    public ResponseEntity<BaseResponse<OrderDTO>> updateOrderStatusFallback(
            Integer orderId, Integer orderState, Exception e) {
        return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
                .body(BaseResponse.error(503, "更新订单状态失败，服务不可用: " + e.getMessage()));
    }

    public ResponseEntity<BaseResponse<OrderDTO>> cancelOrderFallback(Integer orderId, Exception e) {
        return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
                .body(BaseResponse.error(503, "取消订单失败，服务不可用: " + e.getMessage()));
    }

    public ResponseEntity<BaseResponse<OrderDTO>> payOrderFallback(Integer orderId, Exception e) {
        return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
                .body(BaseResponse.error(503, "支付订单失败，服务不可用: " + e.getMessage()));
    }

    public ResponseEntity<BaseResponse<OrderDTO>> completeOrderFallback(Integer orderId, Exception e) {
        return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
                .body(BaseResponse.error(503, "完成订单失败，服务不可用: " + e.getMessage()));
    }
} 